package com.smmisia.gateway.config;

import cn.dev33.satoken.stp.StpInterface;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.smmisia.gateway.entity.SysMenu;
import com.smmisia.gateway.entity.SysRole;
import com.smmisia.gateway.entity.SysRoleMenu;
import com.smmisia.gateway.entity.SysUserRole;
import com.smmisia.gateway.mapper.SysMenuMapper;
import com.smmisia.gateway.mapper.SysRoleMapper;
import com.smmisia.gateway.mapper.SysRoleMenuMapper;
import com.smmisia.gateway.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限验证接口扩展
 * @author smmisia
 * @date 2023/9/27
 */
@Component
@Slf4j
public class StpInterfaceImpl implements StpInterface {

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        Integer userId = Integer.valueOf((String) loginId);

        SysUserRole sysUserRole = sysUserRoleMapper.selectById(userId);
        if (sysUserRole == null) {
            return null;
        }
        Integer roleId = sysUserRole.getRoleId();
        LambdaQueryWrapper<SysRoleMenu> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SysRoleMenu::getRoleId, roleId);
        List<SysRoleMenu> sysRoleMenus = sysRoleMenuMapper.selectList(wrapper);
        List<Integer> list = sysRoleMenus.stream()
                .map(sysRoleMenu -> sysRoleMenu.getMenuId())
                .collect(Collectors.toList());
        List<SysMenu> sysMenus = sysMenuMapper.selectBatchIds(list);
        List<String> perList = sysMenus.stream()
                .map(sysMenu -> sysMenu.getPerms())
                .collect(Collectors.toList());
        return perList;
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        Integer userId = Integer.valueOf((String) loginId);
        SysUserRole sysUserRole = sysUserRoleMapper.selectById(userId);
        Integer roleId = sysUserRole.getRoleId();
        SysRole sysRole = sysRoleMapper.selectById(roleId);
        if (sysUserRole == null) {
            return null;
        }
        List<String> list = new ArrayList<>();
        list.add(sysRole.getRoleKey());
        return list;
    }

}
